<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="always">
        <div slot="header">{{ $route.query.id ? "试题修改" : "试题录入" }}</div>
        <el-form ref="form" label-width="120px" :model="form" :rules="rules">
          <!-- 学科 -->
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              @change="handleSubjectsChange"
              v-model="form.subjectID"
              placeholder="请选择"
            >
              <el-option
                v-for="item in subjectsList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item label="目录：" prop="catalogID">
            <el-select v-model="form.catalogID" placeholder="请选择">
              <el-option
                v-for="item in directorysList"
                :key="item.id"
                :label="item.directoryName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select v-model="form.enterpriseID" placeholder="请选择">
              <el-option
                v-for="item in companysList"
                :key="item.id"
                :label="item.shortName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item class="city" label="城市：" prop="city">
            <el-select
              class="half"
              v-model="form.province"
              placeholder="请选择"
              @change="handleGetArea"
            >
              <el-option
                v-for="item in citysList"
                :key="item.id"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-select class="half" v-model="form.city" placeholder="请选择">
              <el-option
                v-for="item in areaList"
                :key="item.id"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item label="方向：" prop="direction">
            <el-select v-model="form.direction" placeholder="请选择">
              <el-option
                v-for="item in directions"
                :key="item.id"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item label="题型：" prop="questionType">
            <el-radio-group
              @click.native="changeRadio({})"
              v-model="form.questionType"
            >
              <el-radio
                v-for="item in questionType"
                :key="item.value"
                :label="item.value + ''"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度：" prop="difficulty">
            <el-radio-group v-model="form.difficulty">
              <el-radio
                v-for="item in difficulty"
                :key="item.value"
                :label="item.value + ''"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item label="题干：" prop="question">
            <div class="vue-quill-editor">
              <quill-editor
                v-model="form.question"
                :options="editorOption"
                @blur="$refs.form.validateField('question')"
              />
            </div>
          </el-form-item>
          <!-- 选项 -->
          <el-form-item
            v-if="form.questionType !== '3'"
            label="选项："
            prop="options"
          >
            <div
              class="option_item"
              v-for="item in form.options"
              :key="item.code"
            >
              <el-radio
                v-if="form.questionType === '1'"
                @click.native="changeRadio(item)"
                v-model="item.isRight"
                :label="true"
                >{{ item.code }}：</el-radio
              >
              <el-checkbox
                v-if="form.questionType === '2'"
                v-model="item.isRight"
                :label="true"
                >{{ item.code }}：</el-checkbox
              >
              <el-input v-model="item.title" class="radioinput"></el-input>
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :headers="{ Authorization: 'Bearer ' + token }"
                :on-success="
                  (res, file) => {
                    uploadSuccess(item, res, file);
                  }
                "
                :show-file-list="false"
              >
                <img v-if="item.img" :src="item.img" class="avatar" />
                <span v-else>上传图片</span>
                <i class="el-icon-circle-close"></i>
              </el-upload>
            </div>
            <!-- 添加按钮 -->
            <el-button
              size="small"
              type="danger"
              :disabled="form.questionType !== '2'"
              @click="addOption"
              >+增加选项与答案</el-button
            >
          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item label="解析视频：">
            <el-input class="input" v-model="form.videoURL"></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item label="答案解析：" prop="answer">
            <div class="vue-quill-editor">
              <quill-editor
                v-model="form.answer"
                :options="editorOption"
                @blur="$refs.form.validateField('answer')"
              />
            </div>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注：">
            <el-input
              style="width:400px"
              type="textarea"
              :rows="4"
              v-model="form.remarks"
            >
            </el-input>
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item label="试题标签：">
            <el-select
              v-model="form.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择试题标签"
            >
              <el-option
                v-for="item in tagsList"
                :key="item.id"
                :label="item.tagName"
                :value="item.tagName"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 提交按钮 -->
          <el-form-item>
            <el-button type="primary" v-if="!$route.query.id" @click="handleSubmit">确认提交</el-button>
            <el-button type="success" v-else @click="handleUpdate">确认修改</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// import quillEditor from '../components/quill-editor.vue'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { simple } from '@/api/hmmm/subjects.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { list } from '@/api/hmmm/companys.js'
import { list as getDirectorysList } from '@/api/hmmm/directorys.js'
import { list as getTagsList } from '@/api/hmmm/tags.js'
import { add, update, detail } from '@/api/hmmm/questions.js'

import { getToken } from '@/utils/auth'
// import uploadPicture from '../components/uopload-picture.vue'

import { direction, difficulty, questionType } from '@/api/hmmm/constants.js'

export default {
  components: {
    quillEditor
    // optionItem
  },
  data () {
    return {
      // 1. 表单数据
      form: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [
          { code: 'A', title: '', img: '', isRight: false },
          { code: 'B', title: '', img: '', isRight: false },
          { code: 'C', title: '', img: '', isRight: false },
          { code: 'D', title: '', img: '', isRight: false }
        ],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: ''
      },
      // 2. 学科列表数据
      subjectsList: [],
      // 3.1 城市列表数据
      citysList: provinces(),
      // 3.2 城市下地区列表数据
      areaList: [],
      // 4. 企业列表数据
      companysList: [],
      // 5. 方向列表数据
      directions: direction,
      // 6. 学科目录列表数据
      directorysList: [],
      // 7. 学科标签列表数据
      tagsList: [],
      // 8. 富文本编辑器
      editorOption: {
        placeholder: '',
        modules: {
          // 工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
            ['blockquote'], // 引用-----['blockquote']
            ['code-block', 'image', 'link'] // 代码块-----['code-block'] 链接、图片、视频-----['link', 'image', 'video']
          ]
        }
      },
      // 9. 校验对象
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: ['blur', 'change'] }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: ['blur', 'change'] }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: ['blur', 'change'] }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: ['blur', 'change'] }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: ['blur', 'change'] }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: ['blur', 'change'] }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: ['blur', 'change'] }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: ['blur', 'change'] }
        ],
        answer: [
          { required: true, message: '请输入解析', trigger: ['blur', 'change'] }
        ]
      },
      // 10. 试题类型
      questionType,
      // 11. 试题难度
      difficulty,
      // 12. 获取token
      token: getToken()
    }
  },
  created () {
    // 1. 获取学科列表
    this.getSubjectsList()
    // 2. 获取企业列表
    this.getCompanysList()
    // 3. 修改数据回显
    if (this.$route.query.id) {
      this.getQuestion()
    }
  },
  watch: {
    '$route.query': function () {
      if (this.$route.query.id) {
        this.getQuestion()
      } else {
        this.form = {
          subjectID: '',
          catalogID: '',
          enterpriseID: '',
          province: '',
          city: '',
          direction: '',
          questionType: '1',
          difficulty: '1',
          question: '',
          options: [
            { code: 'A', title: '', img: '', isRight: false },
            { code: 'B', title: '', img: '', isRight: false },
            { code: 'C', title: '', img: '', isRight: false },
            { code: 'D', title: '', img: '', isRight: false }
          ],
          videoURL: '',
          answer: '',
          remarks: '',
          tags: ''
        }
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      }
    }
  },
  methods: {
    // 1. 获取学科列表
    async getSubjectsList () {
      const { data: res } = await simple()
      this.subjectsList = res
    },
    // 2. 获取企业列表
    async getCompanysList () {
      const { data: res } = await list()
      this.companysList = res.items
    },
    // 3. 获取城市下地区
    handleGetArea () {
      this.form.city = ''
      this.areaList = citys(this.form.province)
    },
    // 4. 获取学科目录列表
    async getDirectorysList () {
      this.form.catalogID = ''
      const { data: res } = await getDirectorysList(this.form.subjectID)
      this.directorysList = res.items.filter(
        item => this.form.subjectID === item.subjectID
      )
    },
    // 5. 获取学科标签列表
    async getTagsList () {
      this.form.tags = ''
      const { data: res } = await getTagsList(this.form.subjectID)
      this.tagsList = res.items.filter(
        item => this.form.subjectID === item.subjectID
      )
    },
    // 6. 处理学科改变
    handleSubjectsChange () {
      this.getDirectorysList()
      this.getTagsList()
    },
    // 7. 选择单选框
    changeRadio (item) {
      this.form.options.forEach(item => {
        item.isRight = false
      })
      item.isRight = true
    },
    // 8. 点击添加按钮
    addOption () {
      this.form.options.push({
        code: String.fromCharCode(65 + this.form.options.length),
        title: '',
        img: '',
        isRight: false
      })
    },
    // 9. 表单提交
    handleSubmit () {
      this.$refs.form.validate(async flag => {
        if (!flag) return
        // 添加
        // 调用接口
        const data = { ...this.form }
        if (data.tags) {
          data.tags = data.tags.join(',')
        }
        await add(data)
        this.$message.success('添加成功')
        // 跳转页面
        this.$router.push('/questions/list')
      })
    },
    // 10. 获取题目信息
    async getQuestion () {
      const { data } = await detail({ id: this.$route.query.id })
      if (data.tags) {
        data.tags = data.tags.split(',')
      }
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      this.form = data
      const { data: res } = await getDirectorysList({ subjectID: this.form.subjectID })
      this.directorysList = res.items
      const { data: res2 } = await getTagsList({ subjectID: this.form.subjectID })
      this.tagsList = res2.items
      // 滚动顶部
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },
    // 11. 表单修改
    handleUpdate () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const data = { ...this.form }
          if (data.tags) {
            data.tags = data.tags.join(',')
          }
          await update(data)
          this.$message.success('修改成功')
          this.$router.push('/questions/list')
        }
      })
    },
    // 12. 上传照片成功
    uploadSuccess (item, res, file) {
      // res 是相应对象
      // file 选择后的文件对象   file.raw 原始文件对象
      // URL.createObjectURL(file.raw)  本地预览地址
      // item 就是当前的选项对象
      item.img = URL.createObjectURL(file.raw)
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container{
  .app-container{
    margin: 10px 0;
    padding: 0 10px;
  }
}
.el-select {
  width: 400px;
}

.city {
  .half {
    margin-right: 4px;
    width: 198px;
  }
}

.option_item {
  display: flex;
  padding-bottom: 20px;
  align-items: center;
  .radioinput {
    width: 240px;
  }
  .el-radio {
    margin-right: 0px;
    line-height: 35px;
  }
}

.input {
  width: 400px;
}

::v-deep .vue-quill-editor {
  .quill-editor {
    line-height: normal;
    .ql-toolbar.ql-snow {
      height: 38px;
    }
    .ql-container.ql-snow {
      line-height: normal !important;
      height: 200px !important;
      font-size: 14px;
    }
    .ql-snow {
      .ql-tooltip[data-mode="link"]::before {
        content: "请输入链接地址:";
      }
    }
    .ql-editor {
      height: 200px;
    }
  }
}

.avatar-uploader {
  margin-left: 4px;
}
::v-deep .avatar-uploader .el-upload {
  width: 100px;
  height: 60px;
  line-height: 60px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader i {
  position: absolute;
  right: 0;
  top: 0;
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}

.avatar {
  width: 100px;
  height: 60px;
  display: block;
}
</style>
